<template>
	<view class="content" :class="'theme-'+theme">
		<view class="search-box">
			<uni-icons @click="back" type="arrowleft" size="25" color="#252525" />
			<view class="input-box">
				<input type="text" focus :adjust-position="true" :placeholder="defaultKeyword" @input="inputChange"
					v-model.trim="keyword" @confirm="toList()" placeholder-class="placeholder-class"
					confirm-type="search">
			</view>
			<view class="search-btn themeBgColor" @tap="toList()">搜索</view>
		</view>
		<view class="search-keyword">
			<scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y>
				<block v-for="(row,index) in keywordList" :key="index">
					<view class="keyword-entry" hover-class="keyword-entry-tap">
						<view class="keyword-text" @tap.stop="doSearch(keywordList[index].keyword)">
							<rich-text :nodes="row.htmlStr"></rich-text>
						</view>
						<view class="keyword-img" @tap.stop="setKeyword(keywordList[index].keyword)">
							<!-- <image src="/static/HM-search/back.png"></image> -->
						</view>
					</view>
				</block>

			</scroll-view>
			<scroll-view class="keyword-box" v-show="!isShowKeywordList" scroll-y>
				<view class="keyword-block">
					<view class="keyword-list-header">
						<view>历史搜索</view>
						<view v-if="oldKeywordList.length>0">
							<uni-icons color="#737373" type="trash" @tap="oldDelete"></uni-icons>
						</view>
					</view>
					<view class="keyword-wrapper" v-if="oldKeywordList.length>0">
						<view class="keyword" :class="{'no-wrap':!showAll}">
							<view v-for="(k,index) in oldKeywordList" :class="{active:keyword===k.keyWords}"
								@tap="doSearch(k)" :key="index">
								{{k}}
							</view>
						</view>
						<view class="icon" :class="{up:showAll,down:!showAll}">
							<u-icon name="arrow-down" @tap="changeShow"></u-icon>
						</view>
					</view>
					<u-empty v-else text="暂无数据"></u-empty>
				</view>
				<view class="history">
					<view class="history_header">历史购买</view>
					<scroll-view scroll-x v-if="historyGoods.length>0">
						<view class="history_wrapper">
							<view v-for="(history,index) in historyGoods" class="history_item"
								@tap="toDetail(history)" :key="index">
								<view class="history_item_img">
									<image :src="history.thumbnail" mode="widthFix"></image>
									<view class="history_item_img_tag">已买{{history.quantity}}次</view>
									<image v-if="history.status == 'unsale'" class="tag" src="../../static/undercarriage.png"/>
									<image v-if="history.status == 'invalid'" class="tag" src="../../static/failure.png"/>
								</view>
								<view class="history_item_content">
									<view>¥{{history.price}}</view>
									<image src="../../static/cart.png" mode="widthFix" class="history_item_content_add"
										@click.stop="addCart(history)"></image>
								</view>
							</view>
						</view>
					</scroll-view>
          <uni-load-more v-else  :status="'loading'"></uni-load-more>
<!--					<u-empty v-else text="暂无数据"></u-empty>-->
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import {
		queryHistoryPage
	} from '../../api/order/order';
	import {
		deleteAllRecentKey,
		getRecentKey,
		listHotkey
	} from '../../api/product/list';
	import {
		mapState
	} from 'vuex';
	import {
		addToCart
	} from '../../api/cart/cart.js'
import UButton from "../../uview-ui/components/u-button/u-button";
import UPopup from "../../uview-ui/components/u-popup/u-popup";
import copyButton from "../../components/copy";
import OnlineService from "../../components/online-service/online-service";
import OrderTrack from "../../components/order-track/order-track";
	const fromMap = {
		'aftersale': '我的售后单',
		'evaluate': '评价管理'
	}
	const keyMap = {
		'aftersale': 'AftersaleSearchHistoryKeys',
		'evaluate': 'EvaluateSearchHistoryKeys'
	}
	export default {
    components: {
      uniLoadMore,
    },
		data() {
			return {
				defaultKeyword: "",
				keyword: "",
				oldKeywordList: [],
				historyGoods: [],
				keywordList: [],
				forbid: '',
				// 关联搜索展示
				isShowKeywordList: false,
				showAll: false,
				historyData: {},
				isShowPriceUnlogin: 0,
				integralRule: {
					priceShowWay: 1
				},
				from: ''
			}
		},
		computed: {
			...mapState(['hasLogin']),
			storageKey() {
				return keyMap[this.from] || 'OrderSearchHistoryKeys'
			}
		},
		onLoad(option) {
			this.keyword = option.key || ''
			this.from = option.from || ''
			document.title = fromMap[this.from] || '我的订单'
			this.init();
			this.isShowPriceUnlogin = uni.getStorageSync('isShowPriceUnlogin') || 0
			if (uni.getStorageSync('integralRule')) {
				this.integralRule = uni.getStorageSync('integralRule')
			}
		},
		methods: {
			init() {
				this.loadDefaultKeyword();
				this.loadOldKeyword();
				this.loadHistoryGoods()
			},
			// 加载历史购买
			loadHistoryGoods() {
				queryHistoryPage({
					page: 1,
					limit: 6
				}).then(res => {
					if (res.code === 0) {
						this.historyData = res.data
						this.historyGoods = this.historyData.goodsList.records || []
					}
				})
			},
			blur() {
				uni.hideKeyboard()
			},
			changeShow() {
				this.showAll = !this.showAll
			},
			//加载默认搜索关键字
			loadDefaultKeyword() {
				//定义默认搜索关键字，可以自己实现ajax请求数据再赋值,用户未输入时，以水印方式显示在输入框，直接不输入内容搜索会搜索默认关键字
				this.defaultKeyword = "输入订单号或商品名称";
			},
			//加载历史搜索
			loadOldKeyword() {
				this.oldKeywordList = JSON.parse(uni.getStorageSync(this.storageKey) || "[]")
			},
			//监听输入
			inputChange(event) {
				//兼容引入组件时传入参数情况
				// var keyword = event.detail ? event.detail.value : event;
				// if (!keyword) {
				// 	this.keywordList = [];
				// 	this.isShowKeywordList = false;
				// 	return;
				// }
				// this.isShowKeywordList = true;
				//以下示例截取淘宝的关键字，请替换成你的接口
				// uni.request({
				// 	url: 'https://suggest.taobao.com/sug?code=utf-8&q=' + keyword, //仅为示例
				// 	success: (res) => {
				// 		this.keywordList = [];
				// 		this.keywordList = this.drawCorrelativeKeyword(res.data.result, keyword);

				// 	}
				// });
			},
			back() {
				uni.navigateBack()
			},
			addCart(item) {
				if (!this.hasLogin) {
					uni.showModal({
						title: '提示',
						content: '您还未登录，不能进行此操作',
						confirmText: '去登录',
						cancelText: '取消',
						success: (suc) => {
							if (suc.confirm) {
								uni.navigateTo({
									url: '/pages/public/login'
								})
							}
						}
					})
				} else {
					let pType;
					let qType;
					if (item.goodsSourceType === 0) {
						pType = '02';
						qType = 1;
					} else {
						pType = '01';
						qType = 2;
					}
					const good = {
						protocolGoodsId: item.goodsId,
						protocolId: item.protocolId,
						protocolType: pType,
						remainAmount: 1
					}
					/* const params = {
						areaId: uni.getStorageSync('areaId') || this.areaId,
						bizDeptId: uni.getStorageSync('bizDeptInfo').deptId,
						goods: [good],
						isqueryAmount: true,
						queryType: qType
					} */
					const params = {
						areaId: uni.getStorageSync('areaId') || this.historyData.areaId,
						goodsId: item.id,
						num: 1
					}
					addToCart(params).then(res => {
						if (res.code === 0) {
							this.$util.msg('加入购物车成功')
						}else if(res.code === 1001) {
						let msg = ''
						if(res.extra.productAvailability) {
							msg = res.extra.productAvailability.filter(item => !item.canPurchase).map(item => item.message).toString()
						}
						this.$util.msg(res.message+' '+msg)
					} else {
							// if (res.message == '购物车装不下啦，请清理后再试！') {
							// 	this.$refs.fullCartDialog.open()
							// } else {
							this.$util.msg(res.message)
							// }
						}
					})
				}
			},
			//高亮关键字
			drawCorrelativeKeyword(keywords, keyword) {
				var len = keywords.length,
					keywordArr = [];
				for (var i = 0; i < len; i++) {
					var row = keywords[i];
					//定义高亮#9f9f9f
					var html = row[0].replace(keyword, "<span style='color: #9f9f9f;'>" + keyword + "</span>");
					html = '<div>' + html + '</div>';
					var tmpObj = {
						keyword: row[0],
						htmlStr: html
					};
					keywordArr.push(tmpObj)
				}
				return keywordArr;
			},
			//顶置关键字
			setKeyword(index) {
				this.keyword = this.keywordList[index].keyword;
			},
			//清除历史搜索
			oldDelete() {
				const that = this
				uni.showModal({
					title: '提示',
					content: '确定清除历史搜索记录？',
					success: (res) => {
						if (res.confirm) {
							uni.removeStorageSync(that.storageKey)
							that.loadOldKeyword()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			//热门搜索开关
			hotToggle() {
				this.forbid = this.forbid ? '' : '_forbid';
			},
			// 商品列表页
			toList() {
				if (this.keyword)
					this.saveKeyword(this.keyword)
				if (this.from == 'aftersale') {
					getApp().globalData.fromAftersaleSearch = 1
					getApp().globalData.aftersaleSearchKey = this.keyword
				} else if (this.from === 'evaluate') {
					getApp().globalData.fromEvaluateSearch = 1
					getApp().globalData.evaluateSearchKey = this.keyword
				} else {
					getApp().globalData.fromOrderSearch = 1
					getApp().globalData.orderSearchKey = this.keyword
				}
				uni.navigateBack()
				// uni.redirectTo({
				// 	url: `/pages/order/order${this.keyword?'?key='+this.keyword:''}`
				// })
			},
			//执行搜索
			doSearch(keyword, id) {
				keyword = keyword === false ? this.keyword : keyword;
				this.keyword = keyword;
				this.saveKeyword(this.keyword)
			},
			//保存关键字到历史记录
			saveKeyword(keyword) {
				const keyData = uni.getStorageSync(this.storageKey) || "[]"
				let OrderSearchHistoryKeys = JSON.parse(keyData)
				var findIndex = OrderSearchHistoryKeys.indexOf(keyword);
				if (findIndex == -1) {
					OrderSearchHistoryKeys.unshift(keyword);
				} else {
					OrderSearchHistoryKeys.splice(findIndex, 1);
					OrderSearchHistoryKeys.unshift(keyword);
				}
				//最多10个纪录
				OrderSearchHistoryKeys.length > 10 && OrderSearchHistoryKeys.pop();
				uni.setStorageSync(this.storageKey, JSON.stringify(OrderSearchHistoryKeys));
				this.oldKeywordList = OrderSearchHistoryKeys; //更新历史搜索
			},
			toDetail(good) {
				if(good.status!='onsale') return
				uni.navigateTo({
					url: `/pages/product/product?id=${good.id}`
				})
			},
		}
	}
</script>
<style lang="scss">
	view {
		display: block;
	}

	.search-box {
		width: 100%;
		height: 90rpx;
		// background-color: rgb(242, 242, 242);
		padding: 15rpx 2.5%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: sticky;
		border-bottom: 1rpx solid #e2e2e2;
		top: 0;
	}

	.search-box .mSearch-input-box {
		width: 100%;
	}

	.search-box .input-box {
		width: 85%;
		margin-left: 10rpx;
		flex-shrink: 1;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.search-box .search-btn {
		width: 15%;
		height: 100%;
		margin: 0 0 0 2%;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-shrink: 0;
		font-size: 26upx;
		color: #fff;
		border-radius: 60upx;
	}

	.search-box .input-box>input {
		width: 100%;
		height: 60upx;
		font-size: 26upx;
		border: 0;
		border-radius: 60upx;
		-webkit-appearance: none;
		-moz-appearance: none;
		appearance: none;
		padding: 0 30rpx;
		margin: 0;
		background-color: rgb(242, 242, 242);
	}

	.placeholder-class {
		color: #9e9e9e;
	}

	.search-keyword {
		width: 100%;
		background-color: rgb(242, 242, 242);
	}

	.keyword-list-box {
		height: calc(100vh - 110upx);
		padding-top: 10upx;
		border-radius: 20upx 20upx 0 0;
		background-color: #fff;
	}

	.keyword-entry-tap {
		background-color: #eee;
	}

	.keyword-entry {
		width: 94%;
		height: 80upx;
		margin: 0 3%;
		font-size: 30upx;
		color: #333;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: solid 1upx #e7e7e7;
	}

	.keyword-entry image {
		width: 60upx;
		height: 60upx;
	}

	.keyword-entry .keyword-text,
	.keyword-entry .keyword-img {
		height: 80upx;
		display: flex;
		align-items: center;
	}

	.keyword-entry .keyword-text {
		width: 90%;
	}

	.keyword-entry .keyword-img {
		width: 10%;
		justify-content: center;
	}

	.keyword-box {
		background-color: white;
		height: calc(100vh - 110upx);

		.keyword-block {
			padding: 10upx 0;

			.keyword-wrapper {
				display: flex;
				margin: 0 3%;
				align-items: flex-start;

				.keyword {
					flex: 1;
					width: 0;
					display: flex;
					flex-wrap: wrap;
					justify-content: flex-start;

					&.no-wrap {
						white-space: nowrap;
						flex-wrap: nowrap;
						overflow: hidden;
					}

					view {
						border-radius: 40upx;
						padding: 0 30upx;
						margin: 10upx 20upx 10upx 0;
						height: 52upx;
						line-height: 52upx;
						font-size: 24upx;
						background-color: rgb(242, 242, 242);
						color: #aaaaaa;

						&.active {
							color: #d9001b;
							background-color: rgba(#d9001b, 0.1);
						}
					}
				}

				.icon {
					border-radius: 40upx;
					padding: 0 30upx;
					margin: 10upx 0 0 20upx;
					height: 52upx;
					line-height: 52upx;
					font-size: 24upx;
					background-color: rgb(242, 242, 242);
					color: #aaaaaa;

					&.up {
						/deep/.u-icon {
							rotate: 180deg;
							transition: rotate .3s;
						}
					}

					&.down {
						/deep/.u-icon {
							rotate: 0deg;
							transition: rotate .3s;
						}
					}
				}
			}

			.keyword-list-header {
				width: 100%;
				padding: 10upx 3%;
				font-size: 27upx;
				color: #333;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.hide-hot-tis {
				display: flex;
				justify-content: center;
				font-size: 28upx;
				color: #6b6b6b;
			}

			.hot-keyword {
				border-radius: 20rpx;
				border: 2rpx solid rgb(242, 242, 242);
				margin: 0 3%;
				padding: 10rpx 0;

				view {
					color: #aaa;
					padding: 8rpx 20rpx;
					font-size: 24rpx;

					&.active {
						color: #d9001b;
					}
				}
			}
		}
	}

	.history {
		font-size: 26rpx;
		border-radius: 20rpx;
		padding: 10rpx 20rpx;
		margin: 20rpx 3%;
		border: 2rpx solid rgb(242, 242, 242);

		&_header {
			color: #333;
		}

		&_wrapper {
			display: flex;
			align-items: flex-start;
		}

		&_item {
			margin-right: 20rpx;
			margin-top: 10rpx;

			&:last-child {
				margin-right: 0;
			}

			&_img {
				width: 160rpx;
				height: 160rpx;
				position: relative;
				border-radius: 10rpx;

				image {
					width: 100%;
					border: 2rpx solid #e2e2e2;
					border-radius: 10rpx;
				}

				.tag{
					position: absolute;
					width: 120rpx;
					height: 120rpx;
					left: 20rpx;
					top: 20rpx;
				}

				&_tag {
					position: absolute;
					right: 4rpx;
					top: 4rpx;
					font-size: 20rpx;
					background: white;
					border: 2rpx solid #333;
					border-radius: 20rpx;
					transform: scale(0.7);
					transform-origin: right top;
					padding: 4rpx 10rpx;
				}
			}

			&_content {
				margin-top: 10rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				color: #300313;
				font-size: $my-font-size-base;

				&_add {
					width: 60rpx;
				}
			}
		}
	}
</style>
